package Hot100.Medium.BinarySearch;

import java.util.Arrays;

/**
 * 搜索旋转排序数组：输入：nums = [4,5,6,7,0,1,2], target = 0
 *                输出：4
 *
 * 先用LC153的办法找到数组中最小数字，然后在在范围内二分查找
 * 因此一共使用两次二分
 */
public class LC33 {
    public static void main(String[] args) {
        int[] nums = {4, 5, 6, 7, 0, 1, 2};
        int target = 0;
        LC33 solution = new LC33();
        int res = solution.search(nums, target);
        System.out.println(res);


    }

    public int search(int[] nums, int target){
        int n = nums.length;
        int minIndex = findMin(nums);
        int binarySearch1 = lowerBound(nums, -1, minIndex, target);
        if (binarySearch1 < n && nums[binarySearch1] == target) {
            return binarySearch1;
        }
        int binarySearch2 = lowerBound(nums, minIndex - 1, n, target);
        if (binarySearch2 < n && nums[binarySearch2] == target) {
            return binarySearch2;
        }
        return -1;
    }

    public int findMin(int[] nums){
        int n = nums.length;
        int left = -1;
        int right = nums.length - 1;
        while(left + 1 < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] > nums[n -1]){
                left = mid;
            } else {
                right = mid;
            }
        }
        return right;
    }

    public int lowerBound(int[] nums, int left, int right, int target){
        while(left + 1 < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] >= target){
                right = mid;
            } else {
                left = mid;
            }
        }
        return right;
    }

}
